//
//  KLDiscountAddGoodViewController.m
//  KunLun
//
//  Created by Mac on 2017/12/26.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLDiscountAddGoodViewController.h"
#import "STTextView.h"
@interface KLDiscountAddGoodViewController ()
@property(nonatomic, strong) UITextField                     *textFiled;
@property(nonatomic, strong) UITextField                     *numFiled;
@property(nonatomic, strong) NSArray                     *buttonsArray;
@property(nonatomic, strong) STTextView                     *destextView;
@property(nonatomic, strong) UITextField                     *realNameTextfiled;
@property(nonatomic, strong) UITextField                     *idTextfiled;
//封面三张
@property(nonatomic, strong) UIScrollView                     *imageScrollView;
@property(nonatomic, strong) NSMutableArray                     *imageArray;
@property(nonatomic, assign)    CGFloat                         imageViewRight;
@property(nonatomic, strong) NSMutableArray                     *imageUrlsArray;
//详细三张
@property(nonatomic, strong) UIScrollView                     *detailImageScrollView;
@property(nonatomic, strong) NSMutableArray                     *detailImageArray;
@property(nonatomic, assign)    CGFloat                         detailImageViewRight;
@property(nonatomic, strong) NSMutableArray                     *detailImageUrlsArray;
@end

@implementation KLDiscountAddGoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"匀加速商品发布";
    [self configSubView];
    // Do any additional setup after loading the view.
}

- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 200)];
    footer.backgroundColor = [UIColor whiteColor];
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 0, UIScreenWidth - 44, 44)
                                                     text:@"标题:(至少8个字)"
                                                textColor:KL_firstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [footer addSubview:titleLable];

    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(self.insetX, titleLable.bottom, UIScreenWidth - 30, 40)];
    self.textFiled.placeholder = @"请输入标题";
    [footer addSubview:self.textFiled];
    
    
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, self.textFiled.bottom, UIScreenWidth, 0.5)];
    line.backgroundColor = KL_lineColor;
    [footer addSubview:line];
    
    
    STLabel * numLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX,line.bottom, UIScreenWidth - 44, 44)
                                                     text:@"请输入库存"
                                                textColor:KL_firstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [footer addSubview:numLable];
    
    self.numFiled = [[UITextField alloc] initWithFrame:CGRectMake(self.insetX, numLable.bottom, UIScreenWidth - 30, 40)];
    self.numFiled.placeholder = @"请输入库存";
       self.numFiled.keyboardType = UIKeyboardTypeNumberPad;
    [footer addSubview:self.numFiled];
    
    
    UIView * line1 = [[UIView alloc] initWithFrame:CGRectMake(0, self.numFiled.bottom, UIScreenWidth, 0.5)];
    line1.backgroundColor = KL_lineColor;
    [footer addSubview:line1];
    
    //请输入姓名
    STLabel * nameLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX,line1.bottom, UIScreenWidth - 44, 44)
                                                   text:@"请输入姓名"
                                              textColor:KL_firstTextColor
                                                   font:14
                                            isSizetoFit:NO
                                          textAlignment:NSTextAlignmentLeft];
    [footer addSubview:nameLable];
    self.realNameTextfiled = [[UITextField alloc] initWithFrame:CGRectMake(self.insetX, nameLable.bottom, UIScreenWidth - 30, 40)];
    self.realNameTextfiled.placeholder = @"请输入姓名";
    self.realNameTextfiled.keyboardType = UIKeyboardTypeNumberPad;
    [footer addSubview:self.realNameTextfiled];
    UIView * line2 = [[UIView alloc] initWithFrame:CGRectMake(0, self.realNameTextfiled.bottom, UIScreenWidth, 0.5)];
    line1.backgroundColor = KL_lineColor;
    [footer addSubview:line2];
    
    //请输入id
    STLabel * idLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX,line2.bottom, UIScreenWidth - 44, 44)
                                                    text:@"请输入匀加速编号"
                                               textColor:KL_firstTextColor
                                                    font:14
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentLeft];
    [footer addSubview:idLable];
    self.idTextfiled = [[UITextField alloc] initWithFrame:CGRectMake(self.insetX, idLable.bottom, UIScreenWidth - 30, 40)];
    self.idTextfiled.placeholder = @"请输入匀加速编号";
    self.idTextfiled.keyboardType = UIKeyboardTypeNumberPad;
    [footer addSubview:self.idTextfiled];
    UIView * line3 = [[UIView alloc] initWithFrame:CGRectMake(0, self.idTextfiled.bottom, UIScreenWidth, 0.5)];
    line1.backgroundColor = KL_lineColor;
    [footer addSubview:line3];
    
    STLabel * desLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, line3.bottom + 20, UIScreenWidth - 44, 44)
                                                    text:@"商品描述:"
                                               textColor:KL_firstTextColor
                                                    font:14
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentLeft];
    [footer addSubview:desLable];
    
    self.destextView = [[STTextView alloc] initWithFrame:CGRectMake(self.insetX, desLable.bottom, UIScreenWidth - 2*self.insetX, 60)];
    self.destextView.placeholder = @"请输入商品描述";
    [self.destextView st_setBorderWith:1 borderColor:KL_lineColor cornerRadius:5];
    [footer addSubview:self.destextView];
    
    
    STLabel * imagLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, self.destextView.bottom, UIScreenWidth - 2* self.insetX, 44)
                                                    text:@"上传封面图片:(提示，至少上传三张图片)"
                                               textColor:KL_firstTextColor
                                                    font:14
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentLeft];
    [footer addSubview:imagLable];
    
    //封面
    self.imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.insetX, imagLable.bottom, UIScreenWidth- 2*self.insetX, 110)];
    self.imageScrollView.contentSize = CGSizeMake(self.imageScrollView.width, 0);
    [footer addSubview:self.imageScrollView];
    [self resetImageScrollViewFrameWithAddImages:nil  withScrollView:self.imageScrollView];
    
    
    STLabel * detailimagLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, self.imageScrollView.bottom + 20, UIScreenWidth - 2* self.insetX, 44)
                                                          text:@"上传详细图片:(提示，至少上传三张图片)"
                                                     textColor:KL_firstTextColor
                                                          font:14
                                                   isSizetoFit:NO
                                                 textAlignment:NSTextAlignmentLeft];
    [footer addSubview:detailimagLable];
    
    //封面
    self.detailImageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(self.insetX, detailimagLable.bottom, UIScreenWidth- 2*self.insetX, 110)];
    self.detailImageScrollView.contentSize = CGSizeMake(self.imageScrollView.width, 0);
    [footer addSubview:self.detailImageScrollView];
    [self resetImageScrollViewFrameWithAddImages:nil withScrollView:self.detailImageScrollView];
    
    
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(30, self.detailImageScrollView.bottom + 30, UIScreenWidth - 60, 44)
                                                        title:@"确认发布"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:18
                                                 cornerRadius:5
                                              backgroundColor:KL_BlueBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommitButton];
    }];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:confimButton];
    
    self.tableView.tableFooterView = footer;
    footer.height = confimButton.bottom + 20;
    self.tableView.tableFooterView = footer;
}
- (STButton*)deflutButtonWithTitle:(NSString*)title{
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 70, 30)
                                                     title:title
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:15
                                              cornerRadius:5
                                           backgroundColor:KL_BlueBackGroundColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    __weak typeof(self) weakSelf =  self;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlecteTypeButton:sender];
    }];
    return buyButton;
}
#pragma mark --Private Method
- (void)resetImageScrollViewFrameWithAddImages:(NSArray*)images withScrollView:(UIScrollView*)scrollView{
    
    for (UIView * view in scrollView.subviews) {
        [view removeFromSuperview];
    }
    //添加addImageView
    __weak typeof(self) weakSelf =  self;
    STButton * addImageButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)
                                                          title:@""
                                                     titleColor:nil
                                                      titleFont:0
                                                   cornerRadius:0
                                                backgroundColor:KL_backgroundColor
                                                backgroundImage:nil
                                                          image:[UIImage imageNamed:@"sz_xiangce"]];
    addImageButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [addImageButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedAddImageButton:sender];
    }];
    [scrollView addSubview:addImageButton];
    if (scrollView == self.imageScrollView) {
        self.imageViewRight = 100;
    }
    if (scrollView == self.detailImageScrollView) {
        self.detailImageViewRight = 100;
    }
    
    
    for (UIImage * image in images) {
        CGFloat right = 0;
        if (scrollView == self.detailImageScrollView) {
            right = self.detailImageViewRight + 10;
        }else{
            right = self.imageViewRight + 10;
        }
        
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(right, 0, 100, 100)];
        imageView.image = image;
        [scrollView addSubview:imageView];
        
        if (scrollView == self.detailImageScrollView) {
            self.detailImageViewRight = imageView.right;
        }else{
            self.imageViewRight = imageView.right;
        }
        if (scrollView == self.detailImageScrollView) {
            scrollView.contentSize = CGSizeMake(self.detailImageArray.count * 110 + 110, 0);
        }else{
            scrollView.contentSize = CGSizeMake(self.imageArray.count * 110 + 110, 0);
        }
    }
    
}
#pragma mark --Action Method
- (void)onSlecteTypeButton:(UIButton*)sender{
    for (UIButton * button in self.buttonsArray) {
        button.selected = NO;
        sender.selected = YES;
        if (button.selected) {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [button setBackgroundColor:KL_BlueBackGroundColor];
        }else{
            [button setTitleColor:KL_firstTextColor forState:UIControlStateNormal];
            [button setBackgroundColor:KL_backgroundColor];
        }
    }
}
- (void)onSelectedAddImageButton:(UIButton*)button{
    [self showSTImagePickerHandle:^(NSArray<STPhotoModel *> *array) {
        NSMutableArray *newImages = [NSMutableArray new];
        if (button.superview == self.imageScrollView) {
            self.imageArray = [NSMutableArray new];
        }else{
            self.detailImageArray = [NSMutableArray new];
        }
        for (STPhotoModel * model in array) {
            UIImage * image = model.originImage;
            image = image?image:model.thumbImage;
            if (button.superview == self.imageScrollView) {
                
                [self.imageArray addObject:image];
            }else{
                [self.detailImageArray addObject:image];
            }
            
            [newImages addObject:image];
        }
        
        [self resetImageScrollViewFrameWithAddImages:newImages withScrollView:(UIScrollView*)button.superview];
        
    } pickerBlock:^(UIImage *image) {
//        self.imageArray = [NSMutableArray new];
//        self.detailImageArray = [NSMutableArray new];
        NSArray * array;
        if (button.superview == self.imageScrollView) {
            [self.imageArray addObject:image];
            array = self.imageArray;
        }else{
            [self.detailImageArray addObject:image];
            array = self.detailImageArray;
        }
        
        [self resetImageScrollViewFrameWithAddImages:array withScrollView:(UIScrollView*)button.superview];
    }];
}
- (void)onSelectedCommitButton{
    
    if (!self.textFiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"您还未输入标题"];
        return;
    }
    if (!self.numFiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"您还未输入库存"];
        return;
    }
    if (!self.realNameTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"您还未输入姓名"];
        return;
    }
    if (!self.idTextfiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"您还未输入匀加速编号"];
        return;
    }
    if (!self.destextView.text.length) {
        [SVProgressHUD showErrorWithStatus:@"您还未输入描述"];
        return;
    }
    if (self.imageArray.count < 3) {
        [SVProgressHUD showErrorWithStatus:@"至少三张封面图图片"];
        return;
    }
    if (self.detailImageArray.count < 3) {
        [SVProgressHUD showErrorWithStatus:@"至少三张详细图片"];
        return;
    }
    if ([self isCanSendRequest]) {
        [self sendUPZhekouQuanRequest];
        return;
    }
    [SVProgressHUD showWithStatus:@"上传中，请稍后"];
    [self sendImages];
    [self sendDetailImages];
}
- (BOOL)isCanSendRequest{
    if (self.imageUrlsArray.count == self.imageArray.count &&
        self.detailImageUrlsArray.count == self.detailImageArray.count) {
        return YES;
    }
    return NO;
}
- (void)sendImages{
    self.imageUrlsArray = [NSMutableArray new];
    for (UIImage * image in self.imageArray) {
        [KLUtils sendQiNiuWithImage:image handle:^(NSString *imageUrl, NSString *errorDes) {
            [self.imageUrlsArray addObject:imageUrl];
            if ([self isCanSendRequest]) {
                [self sendUPZhekouQuanRequest];
            }
        }];
    }
}
- (void)sendDetailImages{
    self.detailImageUrlsArray = [NSMutableArray new];
    for (UIImage * image in self.detailImageArray) {
        [KLUtils sendQiNiuWithImage:image handle:^(NSString *imageUrl, NSString *errorDes) {
            [self.detailImageUrlsArray addObject:imageUrl];
            if ([self isCanSendRequest]) {
                [self sendUPZhekouQuanRequest];
            }
        }];
    }
}

- (void)sendUPZhekouQuanRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/shop/addgoods",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    
    
    //出售方式，固定价格
    [dic setObject:@"2" forKey:@"sale_type"];
    //图片
    NSString * cover_map = [self.imageUrlsArray componentsJoinedByString:@","];
    [dic setObject:cover_map forKey:@"cover_map"];
    NSString * synopsis = [self.detailImageUrlsArray componentsJoinedByString:@","];
    [dic setObject:synopsis forKey:@"synopsis"];
    //分类
    [dic setObject:self.model.typeId forKey:@"classification"];
    
    if (self.textFiled.text.length) {
        [dic setObject:self.textFiled.text forKey:@"goods_name"];
    }
    if (self.numFiled.text.length) {
        [dic setObject:self.numFiled.text forKey:@"stock"];
    }
    if (self.realNameTextfiled.text.length) {
        [dic setObject:self.realNameTextfiled.text forKey:@"name"];
    }
    if (self.idTextfiled.text.length) {
        [dic setObject:self.idTextfiled.text forKey:@"shop_no"];
    }
    
    if (self.destextView.text.length) {
        [dic setObject:self.destextView.text forKey:@"abstract"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSNumber * num = responseObject[@"data"][@"leave"];
                                                  [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"上传商品成功,您还可以发布%@个该类型的商品",@(num.integerValue-1)]];
                                                 [self.navigationController popViewControllerAnimated:YES];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                             }];
}
@end

